import { Client, PrivateKey } from '@hiveio/dhive';

export const STORE_ADD_HIVE_KEY = 'STORE_ADD_HIVE_KEY';
export const STORE_CLEAR_HIVE_KEY = 'STORE_CLEAR_HIVE_KEY';

export function clearHiveKeyAction() {
  return {
    type: STORE_CLEAR_HIVE_KEY,
  };
}
export function addHiveKeyAction( value) {
  return {
    type: STORE_ADD_HIVE_KEY,
    value,
  };
}

export class Hive {

  constructor() {
    // const options = {
    //   chainId:'beeab0de00000000000000000000000000000000000000000000000000000000',
    //   addressPrefix:'STM',
    // };
    // this.client = new Client('https://api.openhive.network', options);
    const options = {
      chainId:'1c09ee6a7e3fc1da13a357453fe7a01b56005ec6b51e418de49c225d3611f28f',
      addressPrefix:'TST',
    };
    this.client = new Client('/api/v2/steem', options);
  }
  comment(text, username, perm_link, key, parent_author , parent_permlink) {
    console.log(arguments);
    let prvKey = PrivateKey.fromString(key);
    let title = '';
    if (!parent_permlink){
      title = username + '\'s blog';
    }
    if (!parent_author){
      parent_author = '';
    }
    if (!parent_permlink){
      parent_permlink = 'mastodon';
    }

    const op = [
      'comment',
      {
        parent_author: parent_author, // account_name_type
        parent_permlink: parent_permlink,
        author: username, // account_name_type
        permlink: perm_link,
        title: title,
        body: text,
        json_metadata: '',
      },
    ];
    return this.client.broadcast.signOperations([op], prvKey);
  }

  vote(voter, author, perm_link, key, weight = 100) {
    let prvKey = PrivateKey.fromString(key);


    const op = [
      'vote',
      {
        voter: voter, // account_name_type
        author: author, // account_name_type
        permlink: perm_link,
        weight: weight * 100,
      },
    ];
    return this.client.broadcast.signOperations([op], prvKey);
  }

  follow(following, follower, key, follow = true) {
    let prvKey = PrivateKey.fromString(key);

    let type = follow ? 'blog':'';
    const json = JSON.stringify([
      'follow',
      {
        follower: follower,
        following: following,
        what: [type], //null value for unfollow, 'blog' for follow
      },
    ]);

    const data = {
      id: 'follow',
      json: json,
      required_auths: [],
      required_posting_auths: [follower],
    };
    const op = ['custom_json', data];
    return this.client.broadcast.signOperations([op], prvKey);
  }

}
